import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入TOKEN工具
import { getToken } from '../utils/localStorage.js'
// 导入Toast
import { Toast } from 'vant'
// 导入vuex store仓库
import store from '../store/index.js'
// 导入 获取用户数据请求
import { getUser } from '../api/login.js'

import login from '../views/login/index.vue'
import home from '../views/home/index.vue'
import my from '../views/home/my/index.vue'
import company from '../views/home/company/index.vue'
import find from '../views/home/find/index.vue'
import question from '../views/home/question/index.vue'
import info from '../views/home/info/index.vue'
import editInfo from '../views/home/editInfo/index.vue'

// 404网页 要放在最下面
import notFound from '../views/notFound.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/home',
    component: home,
    redirect: '/my', // 默认跳转
    children: [
      {
        path: '/my',
        component: my,
        meta: { needLogin: true, needTab: true }
      },
      {
        path: '/info',
        component: info,
        meta: { needLogin: true }
      },
      {
        path: '/editInfo',
        component: editInfo,
        meta: { needLogin: true }
      },
      {
        path: '/question',
        component: question,
        meta: { needLogin: true, needTab: true }
      },
      {
        path: '/company',
        component: company,
        meta: { needTab: true }
      },
      {
        path: '/find',
        component: find,
        meta: { needTab: true }
      }
    ]
  },
  { path: '/login', component: login },
  {
    path: '*',
    component: notFound,
    meta: {
      title: '404!Not Found!'
    }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach(async (to, from, next) => {
  // 得到要跳转的路由的元素信息中的 needLogin
  var needLogin = to.meta.needLogin
  // 判断 needLogin
  if (needLogin) {
    // 需要登录：判断 token
    // 得到 token
    const token = getToken()
    // console.log(token)
    if (token) {
      // token 存在：判断 user 中是否存在数据
      if (store.state.isLogin) {
        // 其实就是判断了登录的过程
        // 有：向下执行
        next()
      } else {
        // 无：根据 token 重新得到用户信息保存到 vuex 中
        // 发送网络请求
        const res = await getUser(token)
        // 重新将用户信息存入到 vuex中
        store.commit('setUser', res.data)
        store.commit('setLogin', true)
        // 向下执行
        next()
      }
    } else {
      // token 不存在
      // 提示未登录，跳转到登录页面
      Toast.fail('请先登录')

      next('/login?redirect=' + to.fullPath)
    }
  } else {
    // 不需要登录：向下执行
    next()
  }
})

export default router
